package com.kayeah82.application.avatar.qq.security;

import com.kayeah82.application.avatar.qq.exception.BusinessException;
import com.kayeah82.application.avatar.qq.exception.ErrorCode;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kayeah82
 * */
public abstract class CallFrequencyFilter implements SecurityFilter {

    private static final long FREQUENCY_THRESHOLD_MINUTES = 1;

    private Map<String, LocalDateTime> records;

    public CallFrequencyFilter() {
        records = new HashMap<>();
    }

    @Override
    public void doFilter(HttpServletRequest request, SecurityChain chain) {
        String key = getKey(request);
        LocalDateTime now = LocalDateTime.now();
        if (records.containsKey(key)) {
            LocalDateTime last = records.get(key);
            if (last.plusMinutes(FREQUENCY_THRESHOLD_MINUTES).isAfter(now)) {
                throw new BusinessException("[" + key + "] last call took less than " + FREQUENCY_THRESHOLD_MINUTES + " minute", ErrorCode.EC_10002);
            }
        }
        records.put(key, now);
        chain.doFilter(request);
    }

    /**
     * get key by HttpServletRequest.getParameter
     *
     * @return key
     * */
    protected abstract String getKey(HttpServletRequest request);

}
